package com.jd.home.session;

import cn.itcast.core.web.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 远程Session
 * @author lx
 *
 */
public class CacheSessionProvider implements SessionProvider {

	@Autowired
	private Jedis jedis;
	//
	private Integer exp = 30;
	public void setExp(Integer exp) {
		this.exp = exp;
	}

	@Override
	public void setAttributeForUserName(HttpServletRequest request,
                                        HttpServletResponse response, String name, String value) {
		// TODO Auto-generated method stub
		// K   V   USER_SeSSION
		jedis.set(name + getSessionId(request,response), value);
		//用户存活时间  30分钟
		jedis.expire(name + getSessionId(request,response), 60*exp);
	}

	@Override
	public void setAttributeForCode(HttpServletRequest request,
                                    HttpServletResponse response, String name, String value) {
		// TODO Auto-generated method stub
		// K   V  Code_session
		jedis.set(name + getSessionId(request,response), value);
		
		jedis.expire(name + getSessionId(request,response), 60*3);
	}

	@Override
	public String getAttribute(HttpServletRequest request,
                               HttpServletResponse response, String name) {
		// TODO Auto-generated method stub
		return jedis.get(name + getSessionId(request,response));
	}

	@Override
	public String getSessionId(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		//Cookie JSESSIONID  Value
		//Cookie BSESSIONID  Value
		//从Cookie  取
		Cookie[] cookies = request.getCookies();
		if(null != cookies && cookies.length >0){
			for (Cookie cookie : cookies) {
				if(Constants.BSESSIONID.equals(cookie.getName())){
					return cookie.getValue();
				}
			}
		}
		//第一次进来
		String r = UUID.randomUUID().toString().replaceAll("-", "");
		Cookie cookie = new Cookie(Constants.BSESSIONID,r);
		cookie.setPath("/");
		//写回浏览器
		response.addCookie(cookie);
		
		return r;
	}

	

}
